﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Shared;
using Microsoft.Practices.EnterpriseLibrary.Data;

using Syncfusion.Windows.Forms.Tools;
using ctsu.CustomControls;
using ctsu.Data;
using ctsu.Security;

namespace ctsu.Admin.BusLogic
{
	class BLFormLookupImpl: BLFormBaseImpl
	{
		public BLFormLookupImpl(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{

		}

		protected override bool SaveNew(out string message, Database db, DbTransaction trans)
		{
			message = "";
			bool isSuccess = false;

			//sql insert
			string[] exclude = { "ID", "ModifiedBy", "ModifiedWhen" };
			//autoIncrement field is not included
			string sqlIns = Forms.DataUtils.GetSqlInsertStatment(this._tableSchema, exclude, this._formInfo.TableName);

			//sql parameters
			SqlParameter[] aParams = Forms.DataUtils.GetSqlParameters(exclude, false, this._tableSchema);

			//assign parameters
			AssignParameters(aParams);
			try
			{
				DbCommand cmd = db.GetSqlStringCommand(sqlIns);
				DataAccess.AddParamArrayToDbCommand(cmd, aParams);

				int i = db.ExecuteNonQuery(cmd, trans);
				//get key id for new row
				SetKeyValues(db, trans);
				isSuccess = true;
			}
			catch (Exception ex)
			{
				isSuccess = false;
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				if (ex.Message.StartsWith("Violation of UNIQUE KEY"))
				{
					string field = this._fcManager.GetUniqueFieldNotKey();
					FieldContext fc = (FieldContext)this._fcManager.Item(field);
					string val = fc.CurrentValue.ToString();

					StringBuilder sb = new StringBuilder();
					sb.Append("Field: " + field + " ");
					sb.Append("must be unique.");
					sb.Append(Environment.NewLine);
					sb.Append("Value: " + val + " already exists in the table.");
					message = sb.ToString();
				}
				else
					message = ex.Message;
			}
			return isSuccess;
		}	
	}
}
